/*大屏*/
(function () {
	'use strict';

	// 初始化地图
	var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
	var osmAttrib = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
	var osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib, zIndex: 1});

	var map = L.map('allmap', {
		zoomControl: true,
		layers: [osm],
		attributionControl: true
	}).setView([43.99797, 87.283387], 15);

	// 调整地图容器的样式
	map.getContainer().style.zIndex = '1';

	// 确保所有地图相关的弹出层都有较低的 z-index
	map.getPane('mapPane').style.zIndex = '2';
	map.getPane('tilePane').style.zIndex = '1';
	map.getPane('overlayPane').style.zIndex = '3';
	map.getPane('shadowPane').style.zIndex = '2';
	map.getPane('markerPane').style.zIndex = '4';
	map.getPane('tooltipPane').style.zIndex = '5';
	map.getPane('popupPane').style.zIndex = '6';

	// 定义颜色映射
	var colors = {
		1: '#336838',
		2: '#8BBD63',
		3: '#FEE88F',
		4: '#FCCA60',
		5: '#E04B48',
		6: '#A61A2C'
	};

	// 定义路径点
	var latlngs = [
		[44.003774, 87.264333],
		[44.002447, 87.268023],
		[44.001119, 87.271628],
		[43.99797, 87.283387],
		[43.996921, 87.287722],
		[43.995748, 87.292485]
	];

	// 添加标记点
	L.marker([44.003774, 87.264333])
		.addTo(map)
		.bindPopup('上游');

	L.marker([43.995748, 87.292485])
		.addTo(map)
		.bindPopup('下游');

	// 添加分叉口标记
	L.circle([44.001119, 87.271628], {
		color: 'red',
		fillColor: '#f03',
		fillOpacity: 0.5,
		radius: 80
	}).addTo(map)
		.bindPopup('分叉口1');

	L.circle([43.99797, 87.283387], {
		color: 'red',
		fillColor: '#f03',
		fillOpacity: 0.5,
		radius: 80
	}).addTo(map)
		.bindPopup('分叉口2');

	// 创建一个变量来存储当前的路线
	var currentPolyline = null;

	// 从后端获取等级数据并更新路线颜色
	function updatePathColors() {
		fetch('http://localhost:5000/map')
			.then(response => response.json())
			.then(data => {
				// 如果已经有路线了，先移除它
				if (currentPolyline) {
					map.removeLayer(currentPolyline);
				}

				// 使用最新的等级数据创建新路线
				const color = colors[data.rank[0]] || '#2063BE';
				currentPolyline = L.polyline(latlngs, {
					color: color,
					weight: 7,
                    opacity: 0.82
				}).addTo(map);

				// 调整地图视野到路线范围
				map.fitBounds(currentPolyline.getBounds());
			})
			.catch(error => console.error('获取数据失败:', error));
	}

	// 点击地图事件
	map.on('click', function(e) {
		console.log("点击位置: " + e.latlng);
	});

	// 首次加载
	updatePathColors();

	// 每30秒更新一次数据
	setInterval(updatePathColors, 30000);

})();